#include "NetIO.h"

Completed_Queue::Completed_Queue( void )
#ifdef THREAD_SAFE
	: mutex_( )
	, condition_( mutex_ )
#endif
{
}

Completed_Queue::~Completed_Queue( void )
{
	Operation *op;
	while( op = front( ) )
	{
		pop( );
		op->destroy( );
	}
}

int Completed_Queue::dequeue_head( Operation *&op )
{
	op = 0;
#ifdef THREAD_SAFE
	mutex_.acquire( );
#endif

	if( empty( ) )
#ifdef THREAD_SAFE
		condition_.wait( );
#else
		return -1;
#endif

	op = front( );
	pop( );
#ifdef THREAD_SAFE
	mutex_.release( );
#endif
	return 0;
}

int Completed_Queue::enqueue_tail( Operation *op )
{
#ifdef THREAD_SAFE
	mutex_.acquire( );
#endif
	push( op );
#ifdef THREAD_SAFE
	condition_.signal( );
	mutex_.release( );
#endif
	return 0;
}

int Completed_Queue::concat_queue( Operation_Queue *op_queue )
{
	if( op_queue->empty( ) )
		return 0;
#ifdef THREAD_SAFE
	mutex_.acquire( );
#endif
	TAILQ_CONCAT( operations_, op_queue->operations_, field_ );
#ifdef THREAD_SAFE
	condition_.signal( );
	mutex_.release( );
#endif
	return 0;
}
